package com.xce.order.handler;

import com.alibaba.csp.sentinel.adapter.spring.webmvc_v6x.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xce.common.R;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;

import java.io.PrintWriter;

/**
 * @ClassName CustomBlockExceptionHandler
 * @Description TODO
 * @Author lld
 * @Date 2025/7/3 22:30
 * @Version 1.0
 */
@Component
public class CustomBlockExceptionHandler implements BlockExceptionHandler {

    private ObjectMapper mapper = new ObjectMapper();
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response,
                       String resourceName, BlockException e) throws Exception {

        response.setStatus(429);
        response.setContentType("application/json;charset=utf-8");
        PrintWriter writer = response.getWriter();
        R error = R.error(resourceName + "被Sentinel限制了。原因：【" + e.getClass() + "】");
        writer.write(mapper.writeValueAsString(error));
        writer.flush();
        writer.close();
    }
}
